﻿/*
   This source code is offered under the Microsoft Public License (Ms-PL) which is outlined as follows:

   Microsoft Public License (Ms-PL)
   This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.

   1. Definitions
   The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
   A "contribution" is the original software, or any additions or changes to the software.
   A "contributor" is any person that distributes its contribution under this license.
   "Licensed patents" are a contributor's patent claims that read directly on its contribution.

   2. Grant of Rights
   (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
   (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.

   3. Conditions and Limitations
   (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
   (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
   (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
   (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
   (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
 */

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;

using RenewalProjects.Libraries.ParamGate.Attributes;
using RenewalProjects.Libraries.ParamGate.Exceptions;

namespace RenewalProjects.Libraries.ParamGate
{
	/// <summary>
	/// The core parameter processor.
	/// </summary>
	/// <remarks>
	/// By having an array of string arguments, all you need is a class
	/// with properties in it which should be passed to this component.
	/// The class which is used to capture the incoming arguments is called
	/// a parameter container. You can specify attributes to each parameter
	/// to give it more detailed information on how the argument data should
	/// be captured as well as provide validation information. Those attributes
	/// should only derive from the <see cref="ParamGateAttributeBase"/> class.
	/// </remarks>
	[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Param")]
	public static class ParamGateHandler
	{
		/// <summary>
		/// Processes the incoming arguments.
		/// </summary>
		/// <param name="incomingArguments">Input arguments</param>
		/// <param name="parameterContainer">Single instance parameter container</param>
		public static void ProcessArguments(string[] incomingArguments, object parameterContainer)
		{
			if (incomingArguments == null)
			{
				throw new ArgumentNullException("incomingArguments");
			}

			if (parameterContainer == null)
			{
				throw new ArgumentNullException("parameterContainer");
			}

			IDictionary<string, ParameterMetaData> parameterLookup =
			    ParameterContainer.GetParameterMetaDataFromContainer(parameterContainer);

			ParameterNavigator paramNav = new ParameterNavigator(incomingArguments);
			while (paramNav.MoveNext())
			{
				ParameterMetaData meta;

				if (paramNav.Key == null)
				{
					meta = parameterLookup.LookupMetaData(String.Empty);
					if (meta == null)
					{
						throw new ParamGateException("Values without a key has been specified without a defined default parameter");
					}
				}
				else
				{
					meta = parameterLookup.LookupMetaData(paramNav.Key);
					if (meta == null)
					{
						throw new ParamGateException(CultureInfo.CurrentCulture, "Parameter '{0}' has been specified but is not recognised", paramNav.Key);
					}
				}

				if (meta.IsUsed)
				{
					throw new ParamGateException(CultureInfo.CurrentCulture, "Parameter '{0}' has been specified already", paramNav.Key);
				}

				if (paramNav.Values != null)
				{
					if (paramNav.Values.Count == 0)
					{
						ValidateAttributesForProperty(meta.AssociatedAttributes, meta.ParameterName, null);
						parameterContainer.SetParameterValue<Boolean>(meta.PropertyName, true);
					}
					else if (paramNav.Values.Count == 1)
					{
						ValidateAttributesForProperty(meta.AssociatedAttributes, meta.ParameterName, paramNav.Values);
						parameterContainer.SetParameterValue(meta.PropertyName, paramNav.Values[0], true);
					}
					else
					{
						ValidateAttributesForProperty(meta.AssociatedAttributes, meta.ParameterName, paramNav.Values);
						parameterContainer.SetPropertyCollectionValue(meta.PropertyName, paramNav.Values);
					}
				}

				meta.IsUsed = true;
			}

			VerifyExpectedParametersSet(parameterLookup.Values);
		}

		private static void VerifyExpectedParametersSet(IEnumerable<ParameterMetaData> metaDataCollection)
		{
			foreach (ParameterMetaData meta in metaDataCollection)
			{
				if (meta.IsRequired && !meta.IsUsed)
				{
					throw new ParamGateException(CultureInfo.CurrentCulture, "Parameter '{0}' was expected but wasn't specified", meta.ParameterName);
				}
			}
		}

		private static void ValidateAttributesForProperty(IList<ParamGateAttributeBase> associatedAttributes, string parameterName, IList<string> values)
		{
			foreach (ParamGateAttributeBase attr in associatedAttributes)
			{
				if (values == null)
				{
					attr.ValidateParameter(parameterName, null);
				}
				else
				{
					foreach (string value in values)
					{
						attr.ValidateParameter(parameterName, value);
					}
				}
			}
		}

		private static void SetPropertyCollectionValue(this object target, string property, IList<string> values)
		{
			Type objectType = target.GetType();
			PropertyInfo targetProperty =
			    objectType.GetProperty(property,
			                           BindingFlags.Public | BindingFlags.Instance);

			if (targetProperty.PropertyType == typeof(IList<string>)
			    || targetProperty.PropertyType == typeof(IList)
			    || targetProperty.PropertyType == typeof(IEnumerable<string>)
			    || targetProperty.PropertyType == typeof(IEnumerable)
			    || targetProperty.PropertyType == typeof(ICollection<string>)
			    || targetProperty.PropertyType == typeof(ICollection))
			{
				target.SetParameterValue(property, values, false);
				return;
			}

			if (targetProperty.PropertyType == typeof(string[]))
			{
				string[] result = new string[values.Count];
				for (int i = 0; i < result.Length; i++)
				{
					result[i] = values[i];
				}

				target.SetParameterValue(property, result, false);
				return;
			}

			if (((targetProperty.PropertyType.IsPrimitive || targetProperty.PropertyType.IsValueType)
			     && !targetProperty.PropertyType.IsArray)
			    || targetProperty.PropertyType == typeof(String)
			    || targetProperty.PropertyType == typeof(Int32)
			    || targetProperty.PropertyType == typeof(Int16)
			    || targetProperty.PropertyType == typeof(Int64)
			    || targetProperty.PropertyType == typeof(Boolean)
			    || targetProperty.PropertyType == typeof(UInt16)
			    || targetProperty.PropertyType == typeof(UInt32)
			    || targetProperty.PropertyType == typeof(UInt64)
			    || targetProperty.PropertyType == typeof(SByte)
			    || targetProperty.PropertyType == typeof(Byte)
			    || targetProperty.PropertyType == typeof(Double)
			    || targetProperty.PropertyType == typeof(Single)
			    || targetProperty.PropertyType == typeof(Decimal)
			    )
			{
				throw new ParamGateException("Cannot supply multiple values for parameter that expects only one");
			}

			throw new NotSupportedException("Given collection type for property is not supported");
		}

		private static ParameterMetaData LookupMetaData(this IDictionary<string, ParameterMetaData> dic, string paramName)
		{
			ParameterMetaData meta;
			dic.TryGetValue(paramName, out meta);
			return meta;
		}

		private static void SetParameterValue(this object target, string property, object value, bool convertValues)
		{
			Type objectType = target.GetType();
			Type valueType = value.GetType();
			PropertyInfo targetProperty =
			    objectType.GetProperty(property,
			                           BindingFlags.Public | BindingFlags.Instance);

			if (convertValues && !targetProperty.PropertyType.Equals(valueType))
			{
				value = Convert.ChangeType(value, targetProperty.PropertyType, CultureInfo.CurrentCulture);
			}

			targetProperty.SetValue(target, value, null);
		}

		private static void SetParameterValue<T>(this object target, string property, object value)
		{
			Type objectType = target.GetType();
			Type valueType = value.GetType();
			Type expectedType = typeof(T);
			PropertyInfo targetProperty =
			    objectType.GetProperty(property,
			                           BindingFlags.Public | BindingFlags.Instance);

			if (!targetProperty.PropertyType.Equals(expectedType))
			{
				throw new ParamGateException("Invalid type used for this property");
			}

			if (!targetProperty.PropertyType.Equals(valueType))
			{
				value = Convert.ChangeType(value, targetProperty.PropertyType, CultureInfo.CurrentCulture);
			}

			targetProperty.SetValue(target, value, null);
		}
	}
}